package com.maisha.base.dao;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.maisha.DBUtils.BeanToSql;

@Component(value="baseDao")
public class BaseDao {
	
	/**获得dataSource*/
	private DataSource dataSource = C3p0Utils.getDataSource();
	
	private static final Logger log = Logger.getLogger(BaseDao.class);
	
	/** 根据 sql 和 类型 获得对象
	 * @param sql
	 * @param cl
	 * @return
	 * @throws SQLException 
	 */
	public <T> T getResultObject(String sql,Class<T> beanClass,Object... params) throws SQLException{
		ResultSetHandler<T> hander = new BeanHandler<T>(beanClass);
		QueryRunner run = new QueryRunner(dataSource);
		T result = null;
		try {
			 result = run.query(sql, hander, params);
		} catch (SQLException e) {
			log.error("根据 sql 获得对象失败……");
			throw e;
		}
		return result;
	}
	
	/**
	 * 根据slq 和 参数 获得对象 list 集合
	 * @param sql
	 * @param beanClass
	 * @param params
	 * @return
	 * @throws SQLException 
	 */
	public <T> List<T>  getResultList(String sql,Class<T> beanClass,Object... params) throws SQLException{
		List<T> result = null;
		ResultSetHandler<List<T>> hander = new BeanListHandler<T>(beanClass);
		QueryRunner run = new QueryRunner(dataSource);
		try {
			 result = run.query(sql, hander, params);
		} catch (SQLException e) {
			log.error("根据 sql 获得对象列表失败……");
			throw e;
		}
		return result;
	}
	
	/** 保存数据
	 * @param bc
	 * @param obj
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws NoSuchFieldException 
	 * @throws SQLException 
	 */
	public <T> void addObject(Class<T> bc,T obj,boolean constatsNull) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException, SQLException{
		String sql = BeanToSql.insert_Sql(bc, obj, constatsNull);
		if(StringUtils.isNotBlank(sql)){
			QueryRunner run = new QueryRunner(dataSource);
			try {
				run.update(sql);
			} catch (SQLException e) {
				log.error("执行sql 失败……");
				throw e;
			}
		}
	}
	
	/**
	 * 根据slq 和 参数 更新数据
	 * @param sql
	 * @param beanClass
	 * @param params
	 * @return
	 * @throws SQLException 
	 */
	public void updateData(String sql,Object... params) throws SQLException{
		QueryRunner run = new QueryRunner(dataSource);
		try {
			 run.update(sql, params);
		} catch (SQLException e) {
			log.error("根据 sql 修改信息失败……");
			throw e;
		}
	}
	
}
